package models

import (
	"fmt"
	"ginchat/utils"
	"time"

	"gorm.io/gorm"
)

type UserBasic struct {
	gorm.Model
	Name          string
	Password      string
	Salt          string
	Phone         string `valid:"matches=^1[3|4|5|7|8][0-9]{9}$"`
	Email         string `valid:"email"`
	Avatar        string //头像
	Identity      string
	ClientIp      string
	ClientPort    string
	LoginTime     *time.Time
	HeartbeatTime *time.Time
	LogoutTime    *time.Time
	// LogOutTime    time.Time `gorm:"column:logout_time" json:"logout_time"`
	IsLogout   bool
	DeviceInfo string
}

func (table *UserBasic) TableName() string {
	return "user_basic"
}

// 获取用户列表
func GetUserList() []*UserBasic {
	data := make([]*UserBasic, 10)
	utils.DB.Find(&data)
	for _, v := range data {
		fmt.Println(v)
	}
	return data

}

// 创建用户
func CreateUser(user UserBasic) *gorm.DB {
	return utils.DB.Create(&user)
}

// 删除用户
func DeleteUser(user UserBasic) *gorm.DB {
	return utils.DB.Delete(&user)
}

// 更新用户
func UpdateUser(user UserBasic) *gorm.DB {
	return utils.DB.Model(&user).Updates(UserBasic{LoginTime: user.LoginTime})
}

// 根据用户名查询用户
func GetUserByName(name string) *UserBasic {
	user := &UserBasic{}
	utils.DB.Where("name = ?", name).First(user)
	return user
}

// //查找某个用户
func FindById(id uint) UserBasic {
	user := UserBasic{}
	utils.DB.Where("ID = ?", id).First(user)
	return user
}

// 根据用户名和密码查询用户
func GetUserByNameAndPwd(name string, pwd string) *UserBasic {
	user := &UserBasic{}
	utils.DB.Where("name = ? and password = ?", name, pwd).First(user)
	str := fmt.Sprintf("%d", time.Now().Unix())
	temp := utils.MD5Encode(str)
	utils.DB.Model(&user).Where("id = ?", user.ID).Update("Identity", temp)
	return user
}

// 根据手机号查询用户
func GetUserByPhone(phone string) *UserBasic {
	user := &UserBasic{}
	utils.DB.Where("phone = ?", phone).First(user)
	return user
}

// 根据id查询用户
func GetUserById(id uint) *UserBasic {
	user := &UserBasic{}
	utils.DB.Where("id = ?", id).First(user)
	return user
}
